//
//  BootAnimationView.m
//  boot
//
//  Created by Demi on 07/03/2017.
//  Copyright © 2017 Azazie. All rights reserved.
//

#import "BootAnimationView.h"

#import <ReactiveObjC/ReactiveObjC.h>

@interface BootAnimationView ()

@property (nonatomic, weak) UIImageView *imageView;
@property (nonatomic, strong) RACDisposable *disposable;

@end

@implementation BootAnimationView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self comminInit];
    }
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)coder
{
    self = [super initWithCoder:coder];
    if (self) {
        [self comminInit];
    }
    return self;
}

- (void)comminInit
{
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:self.bounds];
    imageView.contentMode = UIViewContentModeScaleAspectFit;
    [self addSubview:imageView];
    _imageView = imageView;
    
    self.backgroundColor = [UIColor whiteColor];
    imageView.backgroundColor = [UIColor whiteColor];
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    _imageView.frame = self.bounds;
}

- (void)startAnimating
{
    NSArray *filePaths = [_imagePaths copy];
    NSTimeInterval duration = _duration;
    NSCParameterAssert(filePaths.count > 0 && duration > 0);
    NSTimeInterval interval = duration / filePaths.count;
    RACSignal *signal = [RACSignal interval:interval onScheduler:[RACScheduler mainThreadScheduler]];
    __block NSUInteger currentIndex = 0;
    @weakify(self);
    self.disposable = [[signal takeUntil:self.rac_willDeallocSignal] subscribeNext:^(id x){
        @strongify(self);
        if (!self) return;
        
        if (currentIndex == filePaths.count)
        {
            [self stopAnimating];
        }
        else
        {
            UIImage *image = [UIImage imageWithContentsOfFile:filePaths[currentIndex]];
            self.imageView.image = image;
            currentIndex++;
        }
    }];
}

- (void)stopAnimating
{
    [self.disposable dispose];
    self.disposable = nil;
}

@end
